const { join, extname } = require('path')
const fs = require('fs')
const http = require('http')
const {createGzip}=require('zlib')

const mimes = {
    '.jpg': 'image/jpeg',
    '.css': 'text/css',
    '.html': 'text/html;charset=utf-8',
    '.js': 'application/javascript',
}

const  rootpath=join(__dirname,'www')
http.createServer((req,res)=>{
    if(req.url!=='./favicon'){
        let pathname=req.url==='/'? './index.html':req.url
        let filepath=join(rootpath,pathname)
        let errpath=join(rootpath,"./404.html")
        if(fs.existsSync(filepath)){
            const ext=extname(filepath)
            const mime=mimes[ext]
            res.setHeader('content-type',mime)
            res.setHeader('expires',new Date(Date.now()+2*1000*60*60*24).toUTCString())
            res.setHeader('Content-Encoding','gzip')
            // res.setHeader('expires','Tus, 18 May 2021 21:03:00 GMT')
            // res.end(fs.readFileSync(filepath))
            //设置压缩方式
            fs.createReadStream(filepath).pipe(createGzip()).pipe(res)
        }else{
            res.statusCode=404
            res.end(fs.readFileSync(errpath))
        }
    }
}).listen(3000,'0.0.0.0')